import logging
import urllib.parse
from collections import defaultdict
import numpy as np
from django.core.files.base import ContentFile
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.views import APIView
from .models import Image, Video, DetectionResult, RealtimeMonitoring, RealtimeDetectionResult
from .serializers import ImageSerializer, VideoSerializer
from rest_framework import generics
import cv2
import os
import tempfile
from django.http import JsonResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .models import Video, DetectionResult
import torch
from yolov7.models.experimental import attempt_load
from yolov7.utils.torch_utils import select_device
from yolov7.utils.datasets import LoadImages
from yolov7.utils.general import check_img_size, non_max_suppression, scale_coords
from yolov7.utils.torch_utils import select_device
import sys
from pathlib import Path
from tqdm import tqdm
from contextlib import redirect_stdout
import io
import requests
from django.core.files.storage import default_storage
from django.conf import settings
from django.utils import timezone
from datetime import timedelta
from utils.response import APIResponse
logger = logging.getLogger(__name__)

class DetectVideoView(APIView):
    permission_classes = [IsAuthenticated]
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 初始化模型
        yolov7_path = Path("D:/program/kitchen/yolov7")
        sys.path.append(str(yolov7_path))
        self.device = select_device('')
        self.model = attempt_load('D:/program/kitchen/yolov7/weights/model_one.pt', map_location=self.device)
        self.stride = int(self.model.stride.max())
        self.imgsz = check_img_size(640, s=self.stride)
        self.model.eval()

    def post(self, request, *args, **kwargs):
        try:
            # 1. 获取视频文件
            video_id = request.data.get('video_id')
            logger.debug(f"Received video_id: {video_id}")
            video = get_object_or_404(Video, id=video_id, user=request.user)
            
            # 设置临时文件和输出文件的目录
            output_dir = os.path.join(settings.MEDIA_ROOT, 'uploads', 'videos')
            os.makedirs(output_dir, exist_ok=True)
            

            temp_video_path = os.path.join(output_dir, os.path.basename(video.video.name))
            logger.debug(f"临时文件路径: {temp_video_path}")
            
            with open(temp_video_path, 'wb') as f:
                f.write(video.video.read())
            
            logger.debug(f"Video downloaded to: {temp_video_path}")

            # 2. 准备输出视频（获取视频属性）
            cap = cv2.VideoCapture(temp_video_path)
            fps = int(cap.get(cv2.CAP_PROP_FPS))
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            cap.release()
            logger.debug(
                f"Video properties - FPS: {fps}, Width: {width}, Height: {height}, Total Frames: {total_frames}")

            # 3. 设置输出路径
            detected_video_filename = 'detected_' + urllib.parse.quote(os.path.basename(video.video.name))
            output_video_path = os.path.join(output_dir, detected_video_filename)
            logger.debug(f"Output video path: {output_video_path}")

            # 4. 初始化视频写入器
            fourcc = cv2.VideoWriter_fourcc(*'avc1')
            out = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))
            logger.debug("Video writer initialized")

            # 5. 加载视频数据集
            dataset = LoadImages(temp_video_path, img_size=self.imgsz, stride=self.stride)
            current_detections = {}
            detection_results = []
            skip_frames = 3  # 跳帧间隔
            frame_counter = 0  # 帧计数器
            last_detections = []  # 上一帧检测结果
            logger.debug("Dataset loaded and variables initialized")

            # 6. 使用重定向抑制所有输出
            with redirect_stdout(io.StringIO()):
                progress_bar = tqdm(
                    enumerate(dataset),
                    total=total_frames,
                    desc="Processing Video Frames",
                    unit="frame",
                    dynamic_ncols=True,
                    bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]'
                )

                for frame_idx, (path, img, im0, vid_cap) in progress_bar:
                    frame_counter += 1

                    # 防御性检查：跳过无效帧
                    if im0 is None or len(im0.shape) < 2 or im0.shape[0] < 10 or im0.shape[1] < 10:
                        logger.error(
                            f"Skipping invalid frame {frame_idx}, shape: {im0.shape if im0 is not None else 'None'}")
                        continue

                    # 预处理并强制维度
                    img = torch.from_numpy(img).to(self.device)
                    img = img.float() / 255.0
                    if img.ndimension() == 3:
                        img = img.unsqueeze(0)  # 确保 [batch=1, channels, height, width]

                    # 推理逻辑
                    if frame_counter % skip_frames == 0:
                        with torch.no_grad():
                            pred = self.model(img, augment=False)[0]
                            pred = non_max_suppression(pred, 0.25, 0.45)
                        last_detections = pred
                    else:
                        pred = last_detections
                        logger.debug(f"Frame {frame_idx} skipped, using last detections")

                    # 9. 处理检测结果
                    current_frame_classes = set()
                    for det in pred:
                        if len(det):
                            if len(im0.shape) < 2:
                                logger.error(f"Invalid frame shape {im0.shape} at frame {frame_idx}")
                                continue  # 跳过无效帧
                            det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape[:2]).round()
                            for *xyxy, conf, cls in det:
                                class_id = int(cls)
                                current_frame_classes.add(class_id)

                                # 跟踪逻辑
                                if class_id in current_detections:
                                    current_detections[class_id]['end_frame'] = frame_idx
                                    current_detections[class_id]['confidence'].append(float(conf))
                                else:
                                    current_detections[class_id] = {
                                        'start_frame': frame_idx,
                                        'end_frame': frame_idx,
                                        'confidence': [float(conf)]
                                    }

                                # 绘制边界框
                                label = f"{self.get_class_name(class_id)} {conf:.2f}"
                                self.plot_one_box(xyxy, im0, label=label, color=self.get_color(class_id))
                    logger.debug(f"Frame {frame_idx} detections processed")

                    # 10. 更新消失的物体
                    for class_id in list(current_detections.keys()):
                        if class_id not in current_frame_classes:
                            self.record_detection(class_id, current_detections.pop(class_id), fps, detection_results)
                    logger.debug(f"Frame {frame_idx} updated disappeared objects")

                    # 11. 写入处理后的帧
                    out.write(im0)
                    logger.debug(f"Frame {frame_idx} written to output video")

                # 12. 关闭进度条
                progress_bar.close()
                logger.debug("Progress bar closed")

            # 13. 处理最后的检测
            for class_id, detection in current_detections.items():
                self.record_detection(class_id, detection, fps, detection_results)
            logger.debug("Final detections processed")

            # 14. 保存结果
            out.release()
            # 检查输出视频文件是否存在
            if not os.path.exists(output_video_path):
                logger.error(f"检测后的视频文件未生成: {output_video_path}")
                return APIResponse.rest_error(message='检测后的视频文件未生成', status=500)
            # 直接使用生成的路径保存视频
            #video.detected_video.name = os.path.join('uploads', 'videos', detected_video_filename)
            self.save_results(video, detected_video_filename, output_video_path, detection_results)
            logger.debug("Results saved successfully")

            # 15. 清理临时文件
            if os.path.exists(temp_video_path):
                os.remove(temp_video_path)

            return APIResponse.rest_success(message="视频检测完成", data={
                "detections": self.format_results(detection_results),
                "detected_video_path": video.detected_video.url,
                "statistics": self._calculate_statistics(detection_results)
            })

        except Exception as e:
            logger.error(f"Error in DetectVideoView.post: {str(e)}", exc_info=True)
            return APIResponse.rest_error(message=str(e), status=500)

    # 辅助方法保持不变
    def get_class_name(self, class_id):
        names = ['person', 'shirtless', 'smoking', 'mask', 'no_mask', 'fire', 'mouse']
        return names[class_id] if class_id < len(names) else str(class_id)

    def get_color(self, class_id):
        np.random.seed(class_id)
        return [int(x) for x in np.random.randint(0, 255, size=3)]

    def plot_one_box(self, xyxy, img, label=None, color=None, line_thickness=3):
        tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1
        c1, c2 = (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3]))
        cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
        if label:
            tf = max(tl - 1, 1)
            t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
            c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
            cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)
            cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255],
                        thickness=tf, lineType=cv2.LINE_AA)

    def record_detection(self, class_id, detection, fps, detection_results):
        avg_conf = sum(detection['confidence']) / len(detection['confidence'])
        detection_results.append({
            'class_id': class_id,
            'class_name': self.get_class_name(class_id),
            'start_time': detection['start_frame'] / fps,
            'end_time': detection['end_frame'] / fps,
            'confidence': avg_conf
        })

    def save_results(self, video, filename, temp_path, detections):
        try:
            # 直接将检测后的视频保存到 models.py 定义的路径，避免保存两份文件。
            with open(temp_path, 'rb') as f:
                video.detected_video.save(filename, ContentFile(f.read()))

            # 记录检测结果到数据库
            for det in detections:
                DetectionResult.objects.create(
                    video=video,
                    class_id=det['class_id'],
                    class_name=det['class_name'],
                    start_time=det['start_time'],
                    end_time=det['end_time'],
                    confidence=det['confidence']
                )

            # 删除临时文件
            if os.path.exists(temp_path):
                os.remove(temp_path)

        except Exception as e:
            logger.error(f"保存检测结果时出错: {str(e)}", exc_info=True)
            raise

    def format_results(self, detections):
        return [{
            'time': f"{int(d['start_time']) // 60}:{int(d['start_time']) % 60:02d}-{int(d['end_time']) // 60}:{int(d['end_time']) % 60:02d}",
            'type': 'error' if d['class_name'] == 'mouse' else 'warning',
            'message': f"检测到{d['class_name']}"
        } for d in detections]

    def _calculate_statistics(self, detections):
        stats = {}
        for d in detections:
            if d['class_name'] not in stats:
                stats[d['class_name']] = {'count': 0, 'total_duration': 0, 'avg_confidence': 0}
            stats[d['class_name']]['count'] += 1
            stats[d['class_name']]['total_duration'] += (d['end_time'] - d['start_time'])
            stats[d['class_name']]['avg_confidence'] += d['confidence']

        for k in stats:
            stats[k]['avg_confidence'] /= stats[k]['count']
        return stats

class ImageUploadView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = ImageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return APIResponse.rest_success(data=serializer.data, status=status.HTTP_201_CREATED)
        return APIResponse.rest_error(message='数据验证失败', data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class UserImagesView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, ** kwargs):
        images = Image.objects.filter(user=request.user)
        serializer = ImageSerializer(images, many=True)
        return APIResponse.rest_success(data=serializer.data)

class VideoUploadView(APIView):
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        try:
            if 'video' not in request.FILES:
                logger.error("请求中没有视频文件")
                return APIResponse.rest_error(message="请提供视频文件", status=400)
            
            video_file = request.FILES['video']
            serializer = VideoSerializer(data={'video': video_file})
            
            if serializer.is_valid():
                try:
                    instance = serializer.save(user=request.user)
                    return APIResponse.rest_success(data=serializer.data, status=200)
                except Exception as e:
                    logger.error(f"保存视频时出错: {str(e)}")
                    return APIResponse.rest_error(message=str(e), status=500)
            else:
                logger.error(f"序列化器验证失败: {serializer.errors}")
                return APIResponse.rest_error(message=serializer.errors, status=400)
                
        except Exception as e:
            logger.error(f"处理视频上传请求时出错: {str(e)}")
            return APIResponse.rest_error(message=str(e), status=500)

class UserVideosView(APIView):
    permission_classes = []
    def get(self, request, *args, **kwargs):
        if request.user.is_anonymous:
            return APIResponse.rest_error(message="用户未认证", status=status.HTTP_401_UNAUTHORIZED)

        videos = Video.objects.filter(user=request.user)
        serializer = VideoSerializer(videos, many=True)
        return APIResponse.rest_success(data=serializer.data)



class VideoHistoryList(generics.ListAPIView):
    queryset = Video.objects.all().order_by('-uploaded_at')[:20]  # 获取最近的20条记录
    serializer_class = VideoSerializer



class ResultList(generics.ListCreateAPIView):

    def get_queryset(self):
        return





@api_view(['GET'])
@permission_classes([IsAuthenticated])
def video_detection_results(request, video_id):
    video = get_object_or_404(Video, id=video_id, user=request.user)

    # Get all detection results for this video
    results = DetectionResult.objects.filter(video=video)

    # Format detection results for frontend
    formatted_results = []
    for result in results:
        start_minutes, start_seconds = divmod(int(result.start_time), 60)
        end_minutes, end_seconds = divmod(int(result.end_time), 60)

        formatted_results.append({
            'time': f"{start_minutes}:{start_seconds:02d}-{end_minutes}:{end_seconds:02d}",
            'type': '',
            'message': f"出现{result.class_name}"
        })

    # Generate statistics
    class_counts = {}
    for result in results:
        if result.class_name in class_counts:
            class_counts[result.class_name] += 1
        else:
            class_counts[result.class_name] = 1

    statistics = {
        'classes': list(class_counts.keys()),
        'counts': list(class_counts.values())
    }

    return APIResponse.rest_success(data={
        'detections': formatted_results,
        'statistics': statistics
    })


from datetime import datetime
def convert_timestamp_to_datetime(timestamp):
    return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

# 获取实时检测的历史数据
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_realtime_data(request):
    try:
        # 获取最近的会话，按开始时间倒序排序
        sessions = RealtimeMonitoring.objects.filter(
            user_id=request.user.id
        ).order_by('-start_time')[:5]
        
        session_data = []

        for session in sessions:
            detections = defaultdict(int)
            results = RealtimeDetectionResult.objects.filter(
                session=session
            ).order_by('start_time')

            detection_details = []

            for result in results:
                detections[result.class_name] += 1
                detection_details.append({
                    'class_id': result.class_id,
                    'class_name': result.class_name,
                    'start_time': result.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'end_time': result.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'confidence': result.confidence,
                    'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S')
                })

            session_data.append({
                'id': session.id,
                'session_id': str(session.session_id),
                'start_time': session.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'end_time': session.end_time.strftime('%Y-%m-%d %H:%M:%S') if session.end_time else None,
                'detections': dict(detections),
                'detection_details': detection_details
            })

        return APIResponse.rest_success(data={'sessions': session_data})

    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=500)

# 获取视频检测的历史数据
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_video_detection_history(request):
    try:
        videos = Video.objects.filter(
            user=request.user
        ).order_by('-uploaded_at')[:5]
        
        video_data = []

        for video in videos:
            detections = defaultdict(int)
            results = DetectionResult.objects.filter(
                video=video
            ).order_by('start_time')

            detection_details = []

            for result in results:
                detections[result.class_name] += 1
                detection_details.append({
                    'class_id': result.class_id,
                    'class_name': result.class_name,
                    'start_time': result.start_time,
                    'end_time': result.end_time,
                    'confidence': float(result.confidence),
                    'count': result.count,
                    'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S')
                })

            video_filename = video.video.name.split('/')[-1] if video.video else None
            video_data.append({
                'id': video.id,
                'video_url': video.video.url,
                'video_name': video_filename,
                'detected_video_url': video.detected_video.url if video.detected_video else None,
                'uploaded_at': video.uploaded_at.strftime('%Y-%m-%d %H:%M:%S'),
                'detection_summary': dict(detections),
                'detection_details': detection_details
            })

        return APIResponse.rest_success(data={
            'videos': video_data,
            'total_videos': len(video_data)
        })

    except Exception as e:
        logger.error(f"获取视频检测历史数据时出错: {str(e)}")
        return APIResponse.rest_error(message=str(e), status=500)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_last_realtime_detection(request):
    """获取最新的实时检测数据"""
    try:
        session = RealtimeMonitoring.objects.filter(
            user_id=request.user.id
        ).order_by('-start_time').first()

        if not session:
            return APIResponse.rest_error(message='没有找到最近的检测会话', status=status.HTTP_404_NOT_FOUND)

        detections = defaultdict(int)
        results = RealtimeDetectionResult.objects.filter(
            session=session
        ).order_by('start_time')

        detection_details = []

        for result in results:
            detections[result.class_name] += 1
            detection_details.append({
                'class_id': result.class_id,
                'class_name': result.class_name,
                'start_time': result.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'end_time': result.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                'confidence': result.confidence,
                'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })

        session_data = {
            'id': session.id,
            'session_id': str(session.session_id),
            'start_time': session.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': session.end_time.strftime('%Y-%m-%d %H:%M:%S') if session.end_time else None,
            'detections': dict(detections),
            'detection_details': detection_details
        }

        return APIResponse.rest_success(data=session_data)

    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_last_video_detection(request):
    """获取最新的视频检测数据"""
    try:
        video = Video.objects.filter(
            user=request.user
        ).order_by('-uploaded_at').first()

        if not video:
            return APIResponse.rest_error(message='没有找到最近的视频检测', status=status.HTTP_404_NOT_FOUND)

        detections = defaultdict(int)
        results = DetectionResult.objects.filter(
            video=video
        ).order_by('start_time')

        detection_details = []

        for result in results:
            detections[result.class_name] += 1
            detection_details.append({
                'class_id': result.class_id,
                'class_name': result.class_name,
                'start_time': result.start_time,
                'end_time': result.end_time,
                'confidence': float(result.confidence),
                'count': result.count,
                'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })

        video_filename = video.video.name.split('/')[-1] if video.video else None
        video_data = {
            'id': video.id,
            'video_url': video.video.url,
            'video_name': video_filename,
            'detected_video_url': video.detected_video.url if video.detected_video else None,
            'uploaded_at': video.uploaded_at.strftime('%Y-%m-%d %H:%M:%S'),
            'detection_summary': dict(detections),
            'detection_details': detection_details
        }

        return APIResponse.rest_success(data=video_data)

    except Exception as e:
        return APIResponse.rest_error(message=str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_day_realtime_data(request, date):
    """获取指定日期的实时检测统计数据"""
    try:
        # 将日期字符串转换为datetime对象
        target_date = datetime.strptime(date, '%Y-%m-%d')
        next_date = target_date + timedelta(days=1)
        
        # 获取指定日期范围内的所有检测结果
        results = RealtimeDetectionResult.objects.filter(
            created_at__gte=target_date,
            created_at__lt=next_date
        ).order_by('created_at')
        
        # 如果没有数据，返回提示信息
        if not results.exists():
            return APIResponse.rest_success(
                message=f'{date}暂无数据',
                data={
                    'date': date,
                    'total_detections': 0,
                    'class_statistics': {},
                    'hourly_statistics': {},
                    'detection_details': []
                }
            )
        
        # 格式化检测结果
        detection_details = []
        for result in results:
            detection_details.append({
                'class_id': result.class_id,
                'class_name': result.class_name,
                'start_time': result.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'end_time': result.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                'confidence': result.confidence,
                'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
            
        # 统计每个类别的检测次数
        class_stats = defaultdict(int)
        for result in results:
            class_stats[result.class_name] += 1
            
        # 按时间统计检测次数
        hourly_stats = defaultdict(int)
        for result in results:
            hour = result.created_at.hour
            hourly_stats[hour] += 1
            
        # 格式化返回数据
        response_data = {
            'date': date,
            'total_detections': len(results),
            'class_statistics': dict(class_stats),
            'hourly_statistics': {
                hour: count for hour, count in sorted(hourly_stats.items())
            },
            'detection_details': detection_details
        }
        
        return APIResponse.rest_success(message=f'{date}日数据获取成功', data=response_data)
        
    except ValueError:
        return APIResponse.rest_error(message='日期格式无效', status=400)
    except Exception as e:
        logger.error(f"获取实时检测统计数据时出错: {str(e)}")
        return APIResponse.rest_error(message=str(e), status=500)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_day_video_data(request, date):
    """获取指定日期的视频检测统计数据"""
    try:
        # 将日期字符串转换为datetime对象
        target_date = datetime.strptime(date, '%Y-%m-%d')
        next_date = target_date + timedelta(days=1)
        
        # 获取指定日期范围内的所有检测结果
        results = DetectionResult.objects.filter(
            created_at__gte=target_date,
            created_at__lt=next_date
        ).select_related('video').order_by('created_at')
        
        # 如果没有数据，返回提示信息
        if not results.exists():
            return APIResponse.rest_success(
                message=f'{date}暂无视频检测数据',
                data={
                    'date': date,
                    'total_detections': 0,
                    'class_statistics': {},
                    'hourly_statistics': {},
                    'detection_details': []
                }
            )
        
        # 格式化检测结果
        detection_details = []
        for result in results:
            video = result.video
            detection_details.append({
                'class_id': result.class_id,
                'class_name': result.class_name,
                'start_time': result.start_time,
                'end_time': result.end_time,
                'confidence': float(result.confidence),
                'created_at': result.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'video_info': {
                    'video_name': video.video.name.split('/')[-1] if video.video else None,
                    'uploaded_at': video.uploaded_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            })
            
        # 统计每个类别的检测次数
        class_stats = defaultdict(int)
        for result in results:
            class_stats[result.class_name] += 1
            
        # 按时间统计检测次数
        hourly_stats = defaultdict(int)
        for result in results:
            hour = result.created_at.hour
            hourly_stats[hour] += 1
            
        # 格式化返回数据
        response_data = {
            'date': date,
            'total_detections': len(results),
            'class_statistics': dict(class_stats),
            'hourly_statistics': {
                hour: count for hour, count in sorted(hourly_stats.items())
            },
            'detection_details': detection_details
        }
        
        return APIResponse.rest_success(message=f'{date}日数据获取成功', data=response_data)
        
    except ValueError:
        return APIResponse.rest_error(message='日期格式无效', status=400)
    except Exception as e:
        logger.error(f"获取视频检测统计数据时出错: {str(e)}")
        return APIResponse.rest_error(message=str(e), status=500)







